'''
Created on Jun 4, 2010

@author: roni
'''
from ns2Scenario import Ns2Scenario
from ns2Observations import Ns2Observations

class DiagnosisEnvironment(object):
    '''
    Contains all the objects required for running a diagnosis simulation and analyze the results. 
    '''
    def __init__(self,file_name = None):
        self.scenario = None
        self.observations = None
        self.added_delays = dict()
        if file_name is not None:
            self.load(file_name)
    
    def save(self,prefix_name):
        self.scenario.save("%s.scenario" % prefix_name)
        self.observations.save("%s.obs" % prefix_name)
        self.save_delays("%s.delays" % prefix_name) 
        
    def load(self,prefix_name):
        scenario = Ns2Scenario()
        scenario.load("%s.scenario" % prefix_name)
        self.scenario = scenario
        
        observations = Ns2Observations()
        observations.load("%s.obs" % prefix_name)
        self.observations = observations
        
        # Set expected delays using flow paths from the observations (but without using the abnormal delays)
        flow_to_path = dict()
        for flow_details in observations.flow_to_details.values():
            flow_to_path[flow_details.flow_id] = flow_details.path
        scenario.calculate_expected_delays(flow_to_path)
        
        self.load_delays("%s.delays" % prefix_name)
        
    def load_delays(self,file_name):
        self.added_delays.clear()
        delays_file = file(file_name,'r') 
        for line in delays_file.readlines():
            parts = line.split(",")
            node = int(parts[0].strip())
            delay = float(parts[1].strip())
            self.added_delays[node]=delay            
        delays_file.close()
        
    def save_delays(self,file_name):
        delays_file = file(file_name,'w') 
        for node in self.added_delays.keys():
            delays_file.write("%s,%s\n" % (node, self.added_delays[node]))
        delays_file.close()

    def __eq__(self,obj):
        if self.scenario.__eq__(obj.scenario)==False:
            return False

        if self.observations.is_equal(obj.observations)==False:        
            return False
        
        if self.added_delays!=obj.added_delays:
            return False
        return True
    
    def is_equal(self,obj):
        return self.__eq__(obj)
    
        